package fxsjdcxt;

import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

public abstract class RsaUtils {
	private static final String KEY_ALGORITHM = "RSA";

	private static final String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJbjsy9yCk6TQECFE+BAntcpOErV0CgLKhDmsrkOb5cbPREH6mHJdszCqYWLmQEtKNgNJsQiuiLnRID3f9T1HD8CAwEAAQ==";
	private static final String privateKey = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAluOzL3IKTpNAQIUT4ECe1yk4StXQKAsqEOayuQ5vlxs9EQfqYcl2zMKphYuZAS0o2A0mxCK6IudEgPd/1PUcPwIDAQABAkB5dC73McQ6GyzMwlGNYHZ6miNFmXVDxjjGAew6KPSJm45JUMKWLgWCktqNF+xo/aAdbUqT8ukCoRNR0XTHG/uBAiEA99Y2dFTkmMTgPo2dffvTlrPVN0J/eJqaPfPkGNywD/sCIQCb3ARDAMc6MbH7ALEvSDt6QBsq5ltyp9qfp9cxvZC9jQIhAOM3LS1yNzIoLT6sLtu16MKdlLjY6mzzsL1jwJdanL/JAiBeqLqh4wgc7O+2jU4PdGRDNEoLvQpPUWizTKGi4QnWRQIhAPI3Jq8/07pzWLIL6f5bOdOfkP20k4zlq2wDdmiJnzKD";

	public static String encrypt(String data) {
		byte[] result = encrypt(data.getBytes(), decodeBase64(publicKey));
		return encodeBase64String(result);
	}

	private static byte[] encrypt(byte[] data, byte[] key) {
		try {
			X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			Key publicKey = keyFactory.generatePublic(x509KeySpec);
			Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			return cipher.doFinal(data);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String decrypt(String data) {
		byte[] result = decrypt(decodeBase64(data), decodeBase64(privateKey));
		return new String(result);
	}

	private static byte[] decrypt(byte[] data, byte[] key) {
		try {
			PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
			Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			return cipher.doFinal(data);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static String encodeBase64String(byte[] data) {
		return Base64.encodeBase64String(data);
	}

	private static byte[] decodeBase64(String data) {
		return Base64.decodeBase64(data);
	}
}